package com.animerank.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.animerank.entity.Anime;
import com.animerank.mapper.AnimeMapper;
import com.animerank.mapper.VoteMapper;
import com.animerank.service.IAnimeService;
import com.animerank.dto.RankDTO;
import com.animerank.dto.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 动漫服务实现类
 */
@Service
public class AnimeServiceImpl extends ServiceImpl<AnimeMapper, Anime> implements IAnimeService {

    @Autowired
    private AnimeMapper animeMapper;

    @Override
    public Result<List<Anime>> searchAnime(String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return Result.fail("搜索关键词不能为空");
        }

        // 搜索动漫
        List<Anime> animeList = animeMapper.searchByTitle(keyword);
        return Result.success(animeList);
    }

    @Autowired
    private VoteMapper voteMapper;

    @Override
    public Result<Map<String, Object>> getMonthlyRank(Integer page, Integer pageSize) {
        // 计算偏移量
        Integer offset = (page - 1) * pageSize;
        
        // 获取月度动漫排行榜（带分页）
        List<Anime> animeList = animeMapper.getMonthlyRank(offset, pageSize);
        List<RankDTO> rankDTOList = new ArrayList<>();

        // 转换为RankDTO列表
        for (int i = 0; i < animeList.size(); i++) {
            Anime anime = animeList.get(i);
            RankDTO rankDTO = new RankDTO();
            rankDTO.setRank(offset + i + 1); // 计算正确的排名
            rankDTO.setAnime(anime);
            // 查询实际票数
            Integer voteCount = voteMapper.countAnimeVotes(anime.getId());
            rankDTO.setVoteCount(voteCount != null ? voteCount : 0);
            rankDTOList.add(rankDTO);
        }

        // 构建返回结果
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("records", rankDTOList);
        resultMap.put("page", page);
        resultMap.put("pageSize", pageSize);
        
        // 这里可以添加总记录数查询，暂时省略
        
        return Result.success(resultMap);
    }

    @Override
    public Result<Anime> getAnimeDetail(Long id) {
        if (id == null || id <= 0) {
            return Result.fail("动漫ID无效");
        }

        // 获取动漫详情
        Anime anime = animeMapper.getAnimeDetail(id);
        if (anime == null) {
            return Result.fail("未找到该动漫");
        }

        // 查询实际票数
        Integer voteCount = voteMapper.countAnimeVotes(id);
        anime.setVotes(voteCount != null ? voteCount : 0);

        return Result.success(anime);
    }

    @Override
    public Result<Integer> getAnimeVoteCount(Long animeId) {
        if (animeId == null || animeId <= 0) {
            return Result.fail("动漫ID无效");
        }

        // 查询动漫投票数
        Integer voteCount = voteMapper.countAnimeVotes(animeId);
        return Result.success(voteCount != null ? voteCount : 0);
    }

    @Override
    public Result<Map<String, Object>> getAllAnimes(String query, Integer page, Integer pageSize, String season, Integer year, String genre, String sortBy) {
        // 参数校验
        if (page == null || page < 1) {
            page = 1;
        }
        if (pageSize == null || pageSize < 1 || pageSize > 100) {
            pageSize = 12;
        }
        
        // 计算偏移量
        Integer offset = (page - 1) * pageSize;
        
        // 查询动漫列表（带分页和筛选）
        List<Anime> animeList = animeMapper.getAnimesWithFilter(offset, pageSize, query, season, year, genre, sortBy);
        
        // 为每个动漫查询实际票数
        for (Anime anime : animeList) {
            Integer voteCount = voteMapper.countAnimeVotes(anime.getId());
            anime.setVotes(voteCount != null ? voteCount : 0);
        }
        
        // 统计符合条件的总数
        Integer totalCount = animeMapper.countAnimesWithFilter(query, season, year, genre);
        
        // 构建返回结果
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("records", animeList);
        resultMap.put("page", page);
        resultMap.put("pageSize", pageSize);
        resultMap.put("total", totalCount);
        resultMap.put("totalPages", (totalCount + pageSize - 1) / pageSize); // 向上取整计算总页数
        
        return Result.success(resultMap);
    }

}